What is this: main:for(...){...} doing?

Posted by David Murdoch on Stack Overflow See other posts from Stack Overflow or by David Murdoch
Published on 2010-06-15T15:25:35Z Indexed on 2010/06/15 15:32 UTC
Read the original article Hit count: 206

Filed under:

I pulled up the NWmatcher source code for some light morning reading and noticed this odd bit of code I'd never seen in javascript before:

main:for(/*irrelevant loop stuff*/){/*...*/}

This snippet can be found in the compileGroup method on line 441 (nwmatcher-1.1.1)

return new Function('c,s,d,h',
    'var k,e,r,n,C,N,T,X=0,x=0;main:for(k=0,r=[];e=N=c[k];k++){' + 
         SKIP_COMMENTS + source + 
    '}return r;'
);

Now I figured out what main: is doing on my own. If you have a loop within a loop and want to skip to the next iteration of the outer loop (without completing the inner OR the outer loop) you can execute continue main. Example:

// This is obviously not the optimal way to find primes...
function getPrimes(max) {
    var primes = [2], //seed
        sqrt = Math.sqrt,
        i = 3, j, s;

    outer: for (; i <= max; s = sqrt(i += 2)) {
        j = 3;
        while (j <= s) {
            if (i % j === 0) {
                // if we get here j += 2 and primes.push(i) are
                // not executed for the current iteration of i
                continue outer;
            }
            j += 2;
        }
        primes.push(i);
    }
    return primes;
}

What is this called?
Are there any browsers that don't support it?
Are there other uses for it other than continue?

© Stack Overflow or respective owner

Related posts about JavaScript